import { AssignRoleItem, ResetUserPassItem, UserItem } from "@/pages/Base/User/data";
import { PageQueryParamType, pageRequest, sendPostRequest, sendGetJsonRequest } from "@/utils/requestEx";
import { userStoarge } from '@/utils/Storage';

/**
 * 分页查询参条件
 * @param paramName 可输，参数名称
 * @param paramKey 可输，参数键名
 */
export interface UserQueryType extends PageQueryParamType {
  paramName?: string;
  paramKey?: string;
}

export async function fetchUsersByRole(params: any) {
  const { roleCode } = params;
  // 判断会话缓存中是否有缓存
  const userList = userStoarge.getItem(roleCode);
  if (userList) {
    // 会话缓存中存在，则取缓存，不再去服务端通讯
    return Promise.resolve(userList);
  }
  const endPointURI = `/dev/user/role/${roleCode}`;
  const res = sendGetJsonRequest(endPointURI, params);
  res.then(data => {
    userStoarge.setItem(roleCode, data);
  });
  return res;
}

export async function fetchAllUser(params: UserQueryType) {
  const endPointURI = '/dev/user/list';
  return pageRequest(endPointURI, params);
}

export async function resetUserPass(params: ResetUserPassItem) {
  const endPointURI = '/dev/user/reset/password';
  return sendPostRequest(endPointURI, params);
}

export async function addUser(params: UserItem) {
  const endPointURI = '/dev/user/insert';
  return sendPostRequest(endPointURI, params);
}

export async function updateUser(params: UserItem) {
  const endPointURI = '/dev/user/update';
  return sendPostRequest(endPointURI, params);
}

export async function deleteUsers(params: any) {
  const endPointURI = `/dev/user/delete`;
  return sendPostRequest(endPointURI, params);
}

export async function fetchRolesByUser(params: any) {
  const { userId } = params;
  const endPointURI = `/dev/user/assigned/role/${userId}`;
  return sendGetJsonRequest(endPointURI, params);
}

export async function assignRolesToUser(params: AssignRoleItem) {
  const endPointURI = `/dev/user/assign/role`;
  return sendPostRequest(endPointURI, params);
}